What is IoC or DI ?IoC stands for Inversion of Control, or DI, Dependency Injection. The term was founded by Martin Fowler, and is now currently supported by several IoC containers, such as Pico, XWork and Spring. IoC allows us to reduce the coupling between components and classes, makes unit testing a whole lot easier and generally promotes good coding style. But what does it do ? Like the name suggests, it will inject certain dependant objects, rather than requiring the depending object to retrieve those objects itself. An exampleSuppose you need a JDBC connection (or Hibernate Session, or ..) in your WebWork Action to communicate with a database. Normally, you would be required to set up a Driver Manager, register a JDBC Driver and get a connection from it.
.. if (driverManager == null){ driverManager = new DriverManager(); driverManager.registerDriver("jdbc.Driver"); } .. if (connection == null){ .. connection = driverManager.getConnection("jdbc://host/db", username, password); } .. Anyway, you get the point. That's a lot of work to get that done. Now, you might want to use some static helper class, store the connection in a ThreadLocal or Session, .. wouldn't it be nice if we could turn this whole 'get the connection' into 'just give me a connection' ? Let's say we develop an Interface that will contain a setter for a JDBC connection: public interface JDBCConnectionAware { public void setJDBCConnection( JDBCConnection connection ); } Now, if we have a class that implements this interface, we have a binding contract that allows us to set a JDBCConnection object on that depending object. public class MyAction implements JDBCConnectionAware { public JDBCConnection connection; .. public String execute() { .. connection.prepareStatement(".."); //here we use the connection object .. return Action.SUCCESS; } .. //as required by the implemented JDBCConnectionAware interface public void setJDBCConnection(JDBCConnection connection){ this.connection = connection; } } So, if look at this example, you see that we do not have to get the connection object from somewhere, nor set it up. We just assume that someone will 'give' us a connection, or 'inject' it. That 'someone' will be our IoC container.
Example in XWorkComing soon. Example in SpringComing soon. Example in PicoComing soon. |